package utils;


import utils.annotations.Aggregated;
import utils.annotations.Update;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author yjt 动态代理
 */
public class DatabaseManipulationProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        var returnType = method.getReturnType();
        if (method.isAnnotationPresent(Update.class)){
            Update update = method.getAnnotation(Update.class);
            String sql = update.sql();
            return SqlFactory.handleUpdate(sql,args);
        }else if(method.isAnnotationPresent(Aggregated.class)){
            Aggregated aggregate = method.getAnnotation(Aggregated.class);
            String sql = aggregate.sql();
            return SqlFactory.singleSelect(SqlFactory.handleQuery(sql,args),returnType);
        } else {
            System.err.println("No annotation found...");
        }
        try {
            return method.invoke(proxy, args);
        } catch (Exception e) {
            System.out.println("Exception found!");
            System.err.println(e.getMessage());
            return null;
        }
    }
}
